package org.springboot.sample.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springboot.sample.po.User;
import org.springboot.sample.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/user")
public class UserController {


	@Autowired
	private UserService userService;
	
	/**
	 * 登录首页
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,Model model){
		model.addAttribute("contextPath",request.getContextPath());
		return "index";
	}
	
    
    /**
     * 登录成功
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/success")
    public String success(User user,Model model,HttpServletRequest request){
    	Boolean exist = userService.isExistUsers(user);
    	model.addAttribute("contextPath",request.getContextPath());
    	if(!exist){    		
    		return "fault";
    	}
    	int id = userService.getUsersIdByNameAndPassword(user);
    	model.addAttribute("userId", id);
    	return"success";
    }
    
    /**
     * 修改用户名
     * @param user
     * @param username
     */
    @RequestMapping(value="/update/{id}",method=RequestMethod.POST)
    public String update(@PathVariable("id")int userId,String updatename,HttpServletRequest request,Model model){
    	userService.updateUsers(userId,updatename);
    	model.addAttribute("contextPath", request.getContextPath());
    	return "index";
    }
    
    
    /**
     * 注册
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/regist")
    public String regist(HttpServletRequest request,Model model){
    	model.addAttribute("contextPath",request.getContextPath());
    	return "regist";
    }
    
    
    /**
     * 注册完成
     * @param user
     * @return
     */
    @RequestMapping("/registSuccess")
    public String registCompleted(User user,HttpServletRequest request,Model model){
    	userService.addUsers(user);
    	model.addAttribute("contextPath",request.getContextPath());
    	return "index";
    }
    
    @RequestMapping("/findAll")
    public String findAll(Model model,HttpServletRequest request){
    	List<User> findAll = userService.findUserList();
    	model.addAttribute("contextPath",request.getContextPath());
    	model.addAttribute("allUser",findAll);
    	return "allUser";
    }
    
    /**
     * 删除用户记录
     * @param userId
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String deleteUsers(@PathVariable("id") int userId){
    	userService.deleteUsers(userId);
    	return "redirect:/user/findAll";
    }
    
    
}
